<!--营业- 结算  - 弹窗组件-->
<template>
  <div>
    <CustomDialog v-model:visible="isShowDialog" top="5vh" curent-class="settlement-dialog">
      <div class="dialog-content">
        <div class="left-box">
          <div class="title">客户支付方式</div>
          <!-- 支付方式列表加载骨架 -->
          <div class="scroll-list" v-if="paymentListLoading">
            <div class="scroll-item skeleton-item" v-for="n in 6" :key="n">
              <div class="skeleton-icon"></div>
              <div class="skeleton-text"></div>
            </div>
          </div>
          <!-- 支付方式列表 -->
          <div class="scroll-list" v-else-if="rechargeTypeList.length">
            <div
              class="scroll-item"
              :class="{ 'scroll-item-active': selectActiveIndex === index }"
              v-for="(item, index) in rechargeTypeList"
              :key="index"
              @click="handleSelect(index, item)"
            >
              <template v-if="item.method === 'on_account'">
                <img
                  v-if="selectActiveIndex === index"
                  class="image"
                  :src="imageData[item.method + item.others.type].activeImage"
                  alt=""
                />
                <img
                  v-else
                  class="image"
                  :src="imageData[item.method + item.others.type].image"
                  alt=""
                />
              </template>
              <template v-else-if="item.method === 'balance'">
                <img
                  v-if="selectActiveIndex === index"
                  class="image"
                  :src="imageData[item.method].activeImage"
                  alt=""
                />
                <img v-else class="image" :src="imageData[item.method].image" alt="" />
              </template>
              <template v-else>
                <img
                  v-if="selectActiveIndex === index"
                  class="image"
                  :src="imageData[item.method].activeImage"
                  alt=""
                />
                <img v-else class="image" :src="imageData[item.method].image" alt="" />
              </template>
              <div class="desc" v-if="item.method === 'balance'">会员支付</div>
              <div class="desc" v-if="item.method === 'cash'">现金支付</div>
              <div class="desc" v-if="item.method === 'alipay'">支付宝</div>
              <div class="desc" v-if="item.method === 'wechat'">微信</div>
              <div class="desc" v-if="item.method === 'on_account' && item.others.type === 1">
                企业挂账
              </div>
              <div class="desc" v-if="item.method === 'on_account' && item.others.type === 2">
                个人挂账
              </div>
              <div class="desc" v-if="item.method === 'integripay'">积分支付</div>
              <div class="desc" v-if="item.method === 'virtual'">
                {{ item.others && item.others.name ? item.others.name : '虚收支付' }}
              </div>
            </div>
            <!-- 当一行有3个以上的元素时，添加占位元素 -->
            <div
              class="scroll-list-item-zhanwei"
              v-for="val in ['val1', 'val2', 'val3', 'val4']"
              :key="val"
            ></div>
          </div>
          <div
            class="balance-box"
            v-if="currentDesktopDiscountInfo && currentDesktopDiscountInfo.is_vip === 1"
          >
            <span>是否开启会员支付：</span>
            <el-switch
              @change="onSwitchOpenBalance"
              v-model="switchOpenBalance"
              active-color="#13ce66"
              inactive-color="#ff4949"
              active-text="是"
              inactive-text="否"
            >
            </el-switch>
          </div>
          <div class="form-box">
            <div class="form-item">
              <div class="dialog-input">
                <input
                  class="input"
                  v-model.trim="dialogKeyword"
                  type="text"
                  placeholder="请输入支付金额"
                  @keyup.enter="onConfirm"
                />
                <img
                  class="image"
                  src="@/assets/images/home/input-clear.png"
                  alt=""
                  @click="handleClearInput"
                  v-if="dialogKeyword"
                />
              </div>
            </div>
          </div>
          <!-- 数字键盘组件 -->
          <NumberKeyboard
            v-model:keyword="dialogKeyword"
            @onInputKeyboard="onInputKeyboard"
            @onCancel="handleClearInput"
            @onConfirm="onConfirm"
            :maxStrLimit="11"
            :isFirstZero="true"
            :loading="confirmLoading"
          />
        </div>
        <div class="line"></div>
        <div class="right-box">
          <div class="title">客户已付金额</div>
          <!-- 已付金额列表加载骨架 -->
          <div class="scroll-list" v-if="payMethodListLoading">
            <div class="scroll-item skeleton-item" v-for="n in 4" :key="n">
              <div class="image-desc">
                <div class="skeleton-icon"></div>
                <div class="skeleton-text"></div>
              </div>
              <div class="money">
                <div class="skeleton-money"></div>
                <div class="skeleton-delete"></div>
              </div>
            </div>
          </div>
          <!-- 已付金额列表 -->
          <div class="scroll-list" v-else>
            <div
              class="scroll-item"
              v-for="(item, index) in payMethodList"
              :key="index"
              @click.stop="handleCancelOrderPay(item.pay_method)"
            >
              <div class="image-desc">
                <template v-if="item.pay_method === 'on_account'">
                  <img class="image" :src="imageData[item.pay_method + item.type].image" alt="" />
                </template>
                <template v-else-if="item.pay_method === 'balance'">
                  <img
                    class="image"
                    v-if="imageData[item.pay_method]"
                    :src="imageData[item.pay_method].image"
                    alt=""
                  />
                  <div v-else class="image"></div>
                </template>
                <template v-else>
                  <img
                    class="image"
                    v-if="imageData[item.pay_method]"
                    :src="imageData[item.pay_method].image"
                    alt=""
                  />
                  <div v-else class="image"></div>
                </template>

                <div class="desc" v-if="item.pay_method === 'balance'">会员支付</div>
                <div class="desc" v-if="item.pay_method === 'cash'">现金支付</div>
                <div class="desc" v-if="item.pay_method === 'alipay'">支付宝</div>
                <div class="desc" v-if="item.pay_method === 'wechat'">微信</div>
                <div class="desc" v-if="item.pay_method === 'on_account' && item.type === 1">
                  企业挂账
                </div>
                <div class="desc" v-if="item.pay_method === 'on_account' && item.type === 2">
                  个人挂账
                </div>
                <div class="desc" v-if="item.pay_method === 'integripay'">积分支付</div>
                <div class="desc" v-if="item.pay_method === 'virtual'">
                  {{ item.name ? item.name : '虚收支付' }}
                </div>
              </div>
              <div class="money">
                <span>￥{{ item.money }}</span>
                <img class="shanchu-icon" src="@/assets/images/bill/shanchu-x.png" alt="" />
              </div>
            </div>
          </div>

          <div
            class="money-desc-box"
            v-if="orderPaymentStatusInfo && orderPaymentStatusInfo.orderInfo"
          >
            <div class="money-desc-left">
              <div>已收金额：￥{{ orderPaymentStatusInfo.payInfo.pay_money || 0 }}</div>
              <div>未收金额：￥{{ notReceivedAmount }}</div>
            </div>
            <div class="money-desc-right">
              <div>应找金额：￥0</div>
              <div class="total-money">
                <span>应付：</span>
                <div>￥{{ orderPaymentStatusInfo.orderInfo.pay_money || 0 }}</div>
              </div>
            </div>
          </div>

          <div class="submit-btn" @click="handleOrderSettlement">
            <div :class="{ loading: settlementLoading }">
              {{ settlementLoading ? '结算中...' : '确认结账' }}
            </div>
          </div>
        </div>
      </div>
    </CustomDialog>

    <!-- 扫码弹框 -->
    <ScannerDialog
      v-model:visible="showScannerDialog"
      @onScan="handleScanResult"
      @onCancel="handleScanCancel"
    />

    <!-- 选择挂账账户的弹窗组件 -->
    <SelectPayCreditDialog
      v-model:isShowDialog="showSelectPayCreditDialog"
      :payCreditType="payCreditType"
      @confirm="onSelectPayCredit"
    />

    <!-- 发票录入提示弹框 -->
    <!-- <InvoiceEntryTipsDialog
      v-model:showDialog="showInvoiceEntryTipsDialog"
      @onCancel="handleInvoiceTipsCancel"
      @onConfirm="handleInvoiceTipsConfirm"
    /> -->

    <!-- 发票录入弹框 -->
    <template v-if="currentDeskDetail">
      <InvoiceEntryDialog
        v-model:showDialog="showInvoiceEntryDialog"
        :orderId="currentDeskDetail.id"
        :orderPaymentStatusInfo="orderPaymentStatusInfo"
        @onConfirm="handleInvoiceConfirm"
      />
    </template>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, nextTick, onMounted, onUnmounted  } from 'vue'
import { ElMessage, ElSwitch } from 'element-plus'
import { useRouter } from 'vue-router'
import CustomDialog from '@/components/CustomDialog/Index.vue'
import NumberKeyboard from '@/components/NumberKeyboard/Index.vue'
import ScannerDialog from '@/components/ScannerDialog/index.vue'
import SelectPayCreditDialog from '@/components/SelectPayCreditDialog/Index.vue'
// import InvoiceEntryTipsDialog from '@/components/InvoiceEntryTipsDialog/Index.vue'
import InvoiceEntryDialog from '@/components/InvoiceEntryDialog/Index.vue'
import { isEmpty, dealAssignDataFunction } from '@/utils/toolsValidate'
import { mathAdd, mathSubtract, strNumberToFixed } from '@/utils/mathjsTool'
import {
  paymentList,
  orderPaymentInfo,
  cashierOrderPay,
  integriPay,
  integripayCancel,
  cashierTradeQuery,
  ashierTradeConfirmPay
} from '@/api/pay'
import { deskRecordEditIsBalance, deskRecordDiscountInfomation } from '@/api/desktop'
import { payMoneyOrderCancel } from '@/api/statistics'
import { bus } from '@/utils/bus'

interface Props {
  showDialog: boolean
  deskDetail?: any
}

interface Emits {
  (e: 'update:showDialog', value: boolean): void
  (e: 'success'): void
}

const props = withDefaults(defineProps<Props>(), {
  showDialog: false,
  deskDetail: null
})

const emit = defineEmits<Emits>()
const router = useRouter()

// 对话框显示状态
const isShowDialog = computed({
  get: () => props.showDialog,
  set: val => emit('update:showDialog', val)
})

// 监听挂账列表刷新事件
const handleGuazhangListRefresh = () => {
  if (isShowDialog.value) {
    getOrderPaymentInfo()
  }
}

onMounted(() => {
  console.log('挂账了');
  
  bus.on('guazhang-list-refresh', handleGuazhangListRefresh)
})

onUnmounted(() => {
  bus.off('guazhang-list-refresh', handleGuazhangListRefresh)
})

// 获取当前桌台详情和折扣信息
const currentDeskDetail = computed(() => props.deskDetail)

// 桌台优惠信息（从 API 获取）
const desktopDiscountInfo = ref<any>({})

const currentDesktopDiscountInfo = computed(() => {
  // 优先使用从 API 获取的优惠信息，如果没有则使用 props.deskDetail 作为后备
  return Object.keys(desktopDiscountInfo.value).length > 0
    ? desktopDiscountInfo.value
    : props.deskDetail || {}
})

// 导入图片资源
import balanceImg from '@/assets/images/home/huiyuanzhifu.png'
import balanceActiveImg from '@/assets/images/home/huiyuanzhifu-active.png'
import cashImg from '@/assets/images/home/xianjin-icon.png'
import enterpriseImg from '@/assets/images/home/qiyeguazhang.png'
import personalImg from '@/assets/images/home/gerenguazhang.png'
import integralImg from '@/assets/images/home/jifendikou.png'
import alipayImg from '@/assets/images/home/zhifubazhifu.png'
import wechatImg from '@/assets/images/home/wechat.png'
import virtualImg from '@/assets/images/home/xushou.png'
import messageTips from '@/components/messageTips'
// 支付方式图片数据
const imageData = ref({
  balance: {
    image: balanceImg,
    activeImage: balanceActiveImg
  },
  cash: {
    image: cashImg,
    activeImage: cashImg
  },
  on_account1: {
    image: enterpriseImg,
    activeImage: enterpriseImg
  },
  on_account2: {
    image: personalImg,
    activeImage: personalImg
  },
  integripay: {
    image: integralImg,
    activeImage: integralImg
  },
  alipay: {
    image: alipayImg,
    activeImage: alipayImg
  },
  wechat: {
    image: wechatImg,
    activeImage: wechatImg
  },
  virtual: {
    image: virtualImg,
    activeImage: virtualImg
  }
})

// 充值类型的列表
const rechargeTypeList = ref([])
// 支付方式列表加载状态
const paymentListLoading = ref(false)
// 已付金额列表加载状态
const payMethodListLoading = ref(false)
// 选中对应的索引
const selectActiveIndex = ref(-1)
// 输入框的金额
const dialogKeyword = ref('')
// 右侧显示对应的支付方式
const payMethodList = ref([])
// 选中的支付方式
const selectActivePayMethod = ref({})
// 订单支付状态
const orderPaymentStatusInfo = ref({})
// 区分挂账账户类型： 1:企业   2：个人
const payCreditType = ref(1)
// 是否显示选择挂账账户的弹窗
const showSelectPayCreditDialog = ref(false)
// 选中的挂账账户id
const selectPayCreditId = ref(null)
// 账户类型(0:主账户 1:子账户)
const creditLevelType = ref(null)
// 按钮节流专用
const buttonDisabled = ref(false)
// 扫码弹框状态
const showScannerDialog = ref(false)
// 扫码结果
const scannerBackValue = ref('')
// 防止input导致重复请求
const isFlag = ref(false)
// 支付接口返回的code
const payment_out_trade_no = ref<string | null>(null)
// 第一次进来得到的金额，切换支付类型，要输入框重新赋值
const settlementMoney = ref('')
// 是否开启会员余额支付
const switchOpenBalance = ref(false)
// 数字键盘确认按钮loading状态
const confirmLoading = ref(false)
// 结算按钮loading状态
const settlementLoading = ref(false)
// 是否显示发票录入提示弹框
const showInvoiceEntryTipsDialog = ref(false)
// 是否显示发票录入弹框
const showInvoiceEntryDialog = ref(false)
// 判断是否需要进行发票录入
const isNeedInvoiceEntry = ref(true)

// 未收金额
const notReceivedAmount = computed(() => {
  if (!orderPaymentStatusInfo.value.payInfo) return '0'

  let moneyValue = mathSubtract(
    parseFloat(orderPaymentStatusInfo.value.payInfo.money),
    mathAdd(
      parseFloat(orderPaymentStatusInfo.value.payInfo.pay_money || 0),
      parseFloat(orderPaymentStatusInfo.value.payInfo.point_money || 0)
    )
  )

  if (moneyValue) moneyValue = parseFloat(moneyValue).toFixed(2)
  return moneyValue >= 0 ? String(moneyValue) : 0
})

// 获取桌台优惠信息
const fetchDeskRecordDiscountInfo = async () => {
  if (!currentDeskDetail.value?.id) return

  try {
    const datas = {
      record_id: currentDeskDetail.value.id
    }
    const res = await deskRecordDiscountInfomation(datas)
    if (res.status === 200) {
      desktopDiscountInfo.value = res.data
    }
  } catch (error) {
    console.error('获取桌台优惠信息失败:', error)
  }
}

// 监听弹框显示状态
watch(isShowDialog, val => {
  if (val) {
    // 重置表单数据
    resetData()
    // 获取桌台优惠信息
    fetchDeskRecordDiscountInfo()
    // 获取支付列表
    getPaymentList()
    // 获取订单支付信息
    getOrderPaymentInfo()
  }
})

// 开启or关闭会员余额支付
const onSwitchOpenBalance = async (val: boolean) => {
  const datas = { status: val ? 1 : 0, record_id: currentDeskDetail.value.id }
  try {
    const res = await deskRecordEditIsBalance(datas)
    if (res.status === 200) {
      ElMessage.success('操作成功')
      selectActiveIndex.value = -1
      // 刷新桌台优惠信息
      await fetchDeskRecordDiscountInfo()
      //   getPaymentList()
      //   getOrderPaymentInfo()
      // 触发父组件刷新数据
      //   emit('success')
    }
  } catch (error) {
    console.error('操作失败:', error)
  }
}

// 获取支付列表
const getPaymentList = async () => {
  const datas = {
    // 是否可使用虚拟支付(0:不可 1:可以)
    balance: 1
  }
  paymentListLoading.value = true
  try {
    const res = await paymentList(datas)
    if (res.status === 200) {
      rechargeTypeList.value = dealAssignDataFunction([], res?.data)
      // 积分支付
      rechargeTypeList.value.push({ method: 'integripay' })
      // 判断是否可以使用会员余额支付
      switchOpenBalance.value = currentDesktopDiscountInfo.value.is_balance === 1
      if (currentDesktopDiscountInfo.value.is_balance === 0) {
        rechargeTypeList.value = rechargeTypeList.value.filter(
          (item: any) => item.method !== 'balance'
        )
      }
    }
  } catch (error) {
    console.error('获取支付列表失败:', error)
  } finally {
    paymentListLoading.value = false
  }
}

// 选中对应的支付方式
const handleSelect = (index: number, item: any) => {
  selectActiveIndex.value = index
  selectActivePayMethod.value = item
  dialogKeyword.value = settlementMoney.value
  // 企业挂账
  if (item.method === 'on_account' && item.others.type === 1) {
    payCreditType.value = 1
    showSelectPayCreditDialog.value = true
    return
  }
  // 个人挂账
  if (item.method === 'on_account' && item.others.type === 2) {
    payCreditType.value = 2
    showSelectPayCreditDialog.value = true
  }
  // 其他支付方式只需要选中，等待用户点击数字键盘确认
}

// 确认提交事件【数字键盘组件】
const onConfirm = async () => {
  if (selectActiveIndex.value === -1) {
    ElMessage.warning('请先选择支付方式')
    return
  }
  console.log('开始支付，设置loading为true')
  confirmLoading.value = true
  try {
    await onSubmitPay()
  } finally {
    console.log('支付完成，设置loading为false')
    confirmLoading.value = false
  }
}

const onSubmitPay = async () => {
  if (selectActivePayMethod.value.method === 'integripay') {
    // 积分支付
    await handleintegriPay()
  } else {
    if (['wechat', 'alipay'].includes(selectActivePayMethod.value.method)) {
      if (!dialogKeyword.value || dialogKeyword.value === '0') {
        ElMessage.warning('请输入支付金额')
        return
      }
      // 显示扫码弹框 - 立即结束loading，因为需要等待扫码
      showScannerDialog.value = true
      return // 立即返回，结束loading状态
    } else {
      // 支付操作
      await handleOrderPay()
    }
  }
}

// 处理扫码结果
const handleScanResult = (scanValue: string) => {
  scannerBackValue.value = scanValue
  showScannerDialog.value = false
  // 支付操作
  handleOrderPay()
}

// 处理扫码取消
const handleScanCancel = () => {
  showScannerDialog.value = false
}

// 清空输入框
const handleClearInput = () => {
  dialogKeyword.value = ''
}

// 接收数字键盘传过来的关键词
const onInputKeyboard = (val: string) => {
  dialogKeyword.value = val
}

// 账单结算
const handleOrderSettlement = async () => {
  // 如果需要发票录入，先显示发票录入提示
  if (isNeedInvoiceEntry.value) {
    // showInvoiceEntryTipsDialog.value = true
    const messageInstance = await messageTips.message(
      {
        title: '确认结账',
        content: '是否确认此账单进行结账吗？',
        isOnCancel: true,
        onCancelText: '关闭',
        onSumbitText: '确认结账'
      },
      async () => {
        await handleInvoiceTipsCancel()
        messageInstance.close && messageInstance.close()
      }
    )
    return
  }

  settlementLoading.value = true
  try {
    const datas = {
      order_id: orderPaymentStatusInfo.value.orderInfo.id, // 订单id
      extra: {
        order_type: 10 // 订单类型(10:桌台订单 20:挂账回款订单 100:充值订单)
      }
    }
    const res = await ashierTradeConfirmPay(datas)
    if (res.status === 200) {
      ElMessage.success('订单结算成功')
      router.replace({ path: '/home' })
      emit('update:showDialog', false)
      emit('success')
    }
  } catch (error) {
    console.error('订单结算失败:', error)
  } finally {
    settlementLoading.value = false
  }
}

// 重置数据
const resetData = () => {
  // 选中对应的索引
  selectActiveIndex.value = -1
  // 输入框的金额
  dialogKeyword.value = ''
  // 右侧显示对应的支付方式
  payMethodList.value = []
  // 选中的支付方式
  selectActivePayMethod.value = {}
  // 扫码枪支付的值
  scannerBackValue.value = ''
  isFlag.value = false
  // 重置发票相关状态
  showInvoiceEntryTipsDialog.value = false
  showInvoiceEntryDialog.value = false
  isNeedInvoiceEntry.value = true
}

// 订单进入结算状态，查询订单支付信息
const getOrderPaymentInfo = async () => {
  const datas = {
    record_id: currentDeskDetail.value.id
  }
  payMethodListLoading.value = true
  try {
    const res = await orderPaymentInfo(datas)
    if (res.status === 200) {
      orderPaymentStatusInfo.value = res.data
      payMethodList.value = dealAssignDataFunction([], res?.data?.payList)

      // 回显结算金额在输入框
      if (
        orderPaymentStatusInfo.value?.orderInfo?.pay_money &&
        orderPaymentStatusInfo.value?.orderInfo?.pay_money !== 0
      ) {
        const currentMoney = orderPaymentStatusInfo.value.payInfo.money
        const mixMoney = mathAdd(
          parseFloat(orderPaymentStatusInfo.value.payInfo.pay_money || 0),
          parseFloat(orderPaymentStatusInfo.value.payInfo.point_money || 0)
        )

        const moneyValue = mathSubtract(parseFloat(currentMoney), mixMoney)
        dialogKeyword.value =
          mixMoney > currentMoney
            ? String(parseFloat(currentMoney).toFixed(2))
            : String(parseFloat(moneyValue).toFixed(2))

        settlementMoney.value =
          mixMoney > currentMoney
            ? String(parseFloat(currentMoney).toFixed(2))
            : String(parseFloat(moneyValue).toFixed(2))
      }
    }
  } catch (error) {
    console.error('获取订单支付信息失败:', error)
  } finally {
    payMethodListLoading.value = false
  }
}

// 支付操作
const handleOrderPay = async () => {
  const datas = {
    order_id: orderPaymentStatusInfo.value.orderInfo.id, // 订单id
    method: selectActivePayMethod.value.method, // 支付方式
    extra: {
      money: dialogKeyword.value || 0 // 支付金额
    }
  }

  // 微信或者支付宝支付
  if (['wechat', 'alipay'].includes(selectActivePayMethod.value.method)) {
    datas.extra.pay_type = 'faceToFace'
    datas.extra.auth_code = scannerBackValue.value
  }

  // 挂账支付
  if (selectActivePayMethod.value.method === 'on_account') {
    // 账户id
    datas.extra.credit_id = selectPayCreditId.value
    // 账户类型(0:主账户 1:子账户)
    datas.extra.type = creditLevelType.value
  }

  // 虚收支付
  if (selectActivePayMethod.value.method === 'virtual') {
    datas.extra.name = selectActivePayMethod.value.others.name
  }

  try {
    const res = await cashierOrderPay(datas)
    clearScanValue()
    if (res.status === 200) {
      if (['wechat', 'alipay'].includes(selectActivePayMethod.value.method)) {
        payment_out_trade_no.value = res.data.payment.out_trade_no
        fetchCashierTradeQuery()
      } else {
        handleClearInput()
        ElMessage.success('操作成功')
        // 订单进入结算状态，查询订单支付信息
        getOrderPaymentInfo()
      }
    }
  } catch (error) {
    clearScanValue()
    console.error('支付失败:', error)
  }
}

// 获取选中的挂账账户id
const onSelectPayCredit = (datas: any) => {
  selectPayCreditId.value = datas.selectPayCreditId
  // 账户类型(0:主账户 1:子账户)
  creditLevelType.value = datas.payType
}

// 积分支付
const handleintegriPay = async () => {
  const datas = {
    order_id: orderPaymentStatusInfo.value.orderInfo.id, // 订单id
    money: dialogKeyword.value || 0 // 支付金额
  }
  try {
    const res = await integriPay(datas)
    if (res.status === 200) {
      handleClearInput()
      ElMessage.success('操作成功')
      // 订单进入结算状态，查询订单支付信息
      getOrderPaymentInfo()
    }
  } catch (error) {
    console.error('积分支付失败:', error)
  }
}

// 取消选中支付的操作【非积分支付和积分支付】
const handleCancelOrderPay = async (payMethod: string) => {
  if (buttonDisabled.value) return
  buttonDisabled.value = true

  try {
    // 积分支付
    if (payMethod === 'integripay') {
      const datas = {
        order_id: orderPaymentStatusInfo.value.orderInfo.id // 订单id
      }
      const res = await integripayCancel(datas)
      if (res.status === 200) {
        ElMessage.success('取消支付成功')
        // 刷新订单信息
        getOrderPaymentInfo()
      }
      return
    }

    // 非积分支付
    const datas = {
      order_id: orderPaymentStatusInfo.value.orderInfo.id, // 订单id
      method: payMethod, // 支付方式(cash:现金支付 balance:会员支付)
      extra: {
        order_type: 10
      }
    }
    const res = await payMoneyOrderCancel(datas)
    if (res.status === 200) {
      ElMessage.success('取消支付成功')
      // 刷新订单信息
      getOrderPaymentInfo()
    }
  } catch (error) {
    console.error('取消支付失败:', error)
  } finally {
    buttonDisabled.value = false
  }
}

// 查询支付宝||微信支付的结果
const fetchCashierTradeQuery = async () => {
  const datas = {
    out_trade_no: payment_out_trade_no.value,
    method: selectActivePayMethod.value.method // 支付方式
  }
  try {
    const res = await cashierTradeQuery(datas)
    if (res.status === 200) {
      if (res.data.isPay) {
        handleClearInput()
        // 订单进入结算状态，查询订单支付信息
        getOrderPaymentInfo()
        ElMessage.success(res.message)
      } else {
        // 显示扫码弹框重试
        showScannerDialog.value = true
      }
    }
  } catch (error) {
    console.error('查询支付结果失败:', error)
  }
}

// 清空扫码枪获取的值
const clearScanValue = () => {
  if (['wechat', 'alipay'].includes(selectActivePayMethod.value.method)) {
    isFlag.value = false
    scannerBackValue.value = ''
  }
}

// 发票录入提示弹框 - 取消事件（直接结账）
const handleInvoiceTipsCancel = () => {
  isNeedInvoiceEntry.value = false
  showInvoiceEntryTipsDialog.value = false
  // 直接执行结算
  handleOrderSettlement()
}

// 发票录入提示弹框 - 确认事件（进入发票录入）
const handleInvoiceTipsConfirm = () => {
  showInvoiceEntryTipsDialog.value = false
  showInvoiceEntryDialog.value = true
}

// 发票录入弹框 - 确认事件（发票录入完成）
const handleInvoiceConfirm = () => {
  isNeedInvoiceEntry.value = false
  showInvoiceEntryDialog.value = false
  // 发票录入完成后，直接执行结算
  handleOrderSettlement()
}
</script>

<style lang="scss" scoped>
.dialog-content {
  display: flex;
  align-items: center;
  justify-content: space-between;

  .left-box {
    width: 516px;

    .title {
      font-size: 18px;
      font-family:
        PingFang SC,
        PingFang SC-Bold;
      font-weight: 700;
      text-align: center;
      color: #333333;
      padding-left: 16px;
    }

    //滚动条整体的大小
    .scroll-list::-webkit-scrollbar {
      width: 6px;
      height: 0;
    }

    //滚动条里滑动的滑块
    .scroll-list::-webkit-scrollbar-thumb {
      height: 60px;
      background: #d2d2d2;
      border-radius: 3px;
    }

    //滚动条底层样式
    .scroll-list::-webkit-scrollbar-track {
      display: none;
    }

    .scroll-list {
      width: 516px;
      height: 248px;
      border: 1px solid #e2e2e2;
      border-radius: 12px;
      overflow-y: auto;
      display: flex;
      align-items: center;
      justify-content: space-between;
      flex-wrap: wrap;
      margin-top: 20px;
      box-sizing: border-box;
      padding: 0 24px 20px 24px;

      .scroll-item {
        box-sizing: border-box;
        padding-left: 6px;
        width: 140px;
        height: 56px;
        background: #f4f4f4;
        border-radius: 12px;
        display: flex;
        align-items: center;
        cursor: pointer;
        margin-top: 20px;
        color: #333333;

        .image {
          flex-shrink: 0;
          width: 30px;
          height: 30px;
          margin-right: 10px;
        }

        .desc {
          font-size: 14px;
          font-family:
            PingFang SC,
            PingFang SC-Regular;
          font-weight: 400;
        }
      }

      .scroll-item-active {
        background: #7c0a03 !important;
        color: #fff !important;
      }

      // 骨架屏样式
      .skeleton-item {
        cursor: default !important;
        pointer-events: none;
        background: #f0f0f0 !important;

        .skeleton-icon {
          width: 30px;
          height: 30px;
          background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
          background-size: 200% 100%;
          animation: skeleton-loading 1.5s infinite;
          border-radius: 4px;
          margin-right: 10px;
        }

        .skeleton-text {
          width: 60px;
          height: 14px;
          background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
          background-size: 200% 100%;
          animation: skeleton-loading 1.5s infinite;
          border-radius: 4px;
        }
      }
    }

    // flex布局的列表进行占位操作
    .scroll-list-item-zhanwei {
      width: 140px;
      overflow: hidden;
    }

    .balance-box {
      display: flex;
      align-items: center;
      margin-top: 20px;
      font-size: 14px;
      color: #333333;
    }

    .form-box {
      margin-top: 20px;
      margin-bottom: 30px;

      .form-item {
        .dialog-input {
          width: 516px;
          height: 48px;
          background: #ffffff;
          border: 1px solid #d2d2d2;
          border-radius: 12px;
          box-sizing: border-box;
          padding: 0 20px;
          display: flex;
          align-items: center;
          justify-content: space-between;

          .input {
            width: 400px;
            font-size: 14px;
            font-family:
              PingFang SC,
              PingFang SC-Regular;
            font-weight: 400;
            text-align: left;
            color: #333333;
            outline: none;
            border: none;
          }

          .image {
            flex-shrink: 0;
            width: 24px;
            height: 24px;
            cursor: pointer;
          }
        }
      }
    }
  }

  .line {
    width: 1px;
    height: 718px;
    background: #e2e2e2;
    margin-left: 30px;
    margin-top: 58px;
  }

  .right-box {
    margin-left: 30px;

    .title {
      font-size: 18px;
      font-family:
        PingFang SC,
        PingFang SC-Bold;
      font-weight: 700;
      text-align: center;
      color: #333333;
      padding-left: 16px;
    }

    .scroll-list {
      background: #f4f4f4;
      width: 504px;
      height: 527px;
      border: 1px solid #e2e2e2;
      border-radius: 12px;
      overflow-y: auto;
      margin-top: 20px;
      box-sizing: border-box;
      padding: 0 24px 20px 24px;

      .scroll-item {
        box-sizing: border-box;
        padding: 0 20px;
        width: 448px;
        height: 48px;
        background: #ffffff;
        border-radius: 12px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-top: 20px;
        color: #333333;
        cursor: pointer;

        .image-desc {
          display: flex;
          align-items: center;

          .image {
            flex-shrink: 0;
            width: 30px;
            height: 30px;
            margin-right: 20px;
          }

          .desc {
            font-size: 16px;
            font-family:
              PingFang SC,
              PingFang SC-Regular;
            font-weight: 400;
          }
        }

        .money {
          display: flex;
          align-items: center;

          > span {
            font-size: 16px;
            font-family:
              PingFang SC,
              PingFang SC-Regular;
            font-weight: 400;
            color: #333333;
          }

          .shanchu-icon {
            flex-shrink: 1;
            width: 20px;
            height: 20px;
            margin-left: 10px;
          }
        }
      }

      // 右侧骨架屏样式
      .skeleton-item {
        cursor: default !important;
        pointer-events: none;
        background: #f0f0f0 !important;

        .image-desc {
          .skeleton-icon {
            width: 30px;
            height: 30px;
            background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
            background-size: 200% 100%;
            animation: skeleton-loading 1.5s infinite;
            border-radius: 4px;
            margin-right: 20px;
          }

          .skeleton-text {
            width: 80px;
            height: 16px;
            background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
            background-size: 200% 100%;
            animation: skeleton-loading 1.5s infinite;
            border-radius: 4px;
          }
        }

        .money {
          display: flex;
          align-items: center;

          .skeleton-money {
            width: 60px;
            height: 16px;
            background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
            background-size: 200% 100%;
            animation: skeleton-loading 1.5s infinite;
            border-radius: 4px;
            margin-right: 10px;
          }

          .skeleton-delete {
            width: 20px;
            height: 20px;
            background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
            background-size: 200% 100%;
            animation: skeleton-loading 1.5s infinite;
            border-radius: 4px;
          }
        }
      }
    }

    //滚动条整体的大小
    .scroll-list::-webkit-scrollbar {
      width: 6px;
      height: 0;
    }

    //滚动条里滑动的滑块
    .scroll-list::-webkit-scrollbar-thumb {
      height: 100px;
      background: #d2d2d2;
      border-radius: 3px;
    }

    //滚动条底层样式
    .scroll-list::-webkit-scrollbar-track {
      display: none;
    }

    .money-desc-box {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-top: 30px;

      .money-desc-left {
        font-size: 18px;
        font-family:
          PingFang SC,
          PingFang SC-Regular;
        font-weight: 400;
        text-align: left;
        color: #333333;

        > div:first-child {
          margin-bottom: 30px;
        }
      }

      .money-desc-right {
        font-size: 18px;
        font-family:
          PingFang SC,
          PingFang SC-Regular;
        font-weight: 400;
        color: #333333;

        .total-money {
          margin-top: 30px;
          display: flex;
          align-items: flex-end;

          > div {
            font-size: 36px;
            font-family:
              PingFang SC,
              Bold;
            font-weight: 700;
            color: #7c0a03;
          }
        }
      }
    }

    .submit-btn {
      height: 52px;
      margin-top: 30px;
      display: flex;
      align-items: center;
      justify-content: center;

      > div {
        width: 456px;
        height: 52px;
        background: #7c0a03;
        border-radius: 12px;
        line-height: 52px;
        font-size: 18px;
        font-family:
          PingFang SC,
          PingFang SC-Regular;
        font-weight: 400;
        text-align: center;
        color: #f8f8f8;
        cursor: pointer;
        transition: all 0.3s ease;

        &.loading {
          background: #a0a0a0;
          cursor: not-allowed;
          opacity: 0.7;
        }

        &:not(.loading):hover {
          background: #8c1a13;
        }
      }
    }
  }
}

// 骨架屏动画
@keyframes skeleton-loading {
  0% {
    background-position: -200% 0;
  }
  100% {
    background-position: 200% 0;
  }
}
</style>
<style>
.settlement-dialog {
  max-height: unset !important;
}
</style>
